// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
// about ai - start
async function chatCompletion({messages,summarize=false}) {
	// console.log('messagesmessages',messages)
	const llmManager = uniCloud.ai.getLLMManager()
	let res = await llmManager.chatCompletion({
		messages,
		tokensToGenerate:3000
	})
	// console.error('totalTokens',res,res.usage.totalTokens);
	if(!summarize && res.usage.totalTokens > 500){
		messages.push({
			"content": res.reply,
			"role": "assistant"
		},{
			"content": "请简要总结上述全部对话",
			"role": "user"
		})
		// console.log('messages------->',messages)
		let {reply} = await chatCompletion({messages,summarize:true})
		res.summarize = reply
		// console.log('res.summarize = reply',res.summarize)
	}
	return res
}
// about ai - end

async function getAccessToken(){
	const res = await uniCloud.httpclient.request('https://aip.baidubce.com/oauth/2.0/token',{
		data:{
			grant_type:'client_credentials',
			client_id:'WqXE0ORZHfaTX6Vrbt3IXoot',
			client_secret:'KGaivyIqn4V5W4k7lzxwZmcWRm3VOiTy'
		},
		contentType: 'json', // 指定以application/json发送data内的数据
		dataType: 'json' // 指定返回值为json格式，自动进行parse
	})
	return res
}
module.exports = {
	_before: function () { // 通用预处理器
	},
	/**
	 * chat
	 * @param {array} messages [{role: 'user',content: 'uni-app是什么，20个字以内进行说明'}]
	 * @returns {object} 
	 */
	async chat(messages){
		console.log(messages);
		if (!Array.isArray(messages)) {
			return {errCode: -1,errMsg: '参数必须为数组'}
		}
		const res = await chatCompletion({messages})
		return res;
	},
	/**
	 * draw
	 */
	async draw(){
		const res = await getAccessToken()
		const {access_token}=res.data
		// return access_token
		// const access_token= '24.9fdd6921b70989fd690647ace1d9e596.2592000.1687688632.282335-34021048'
		// const res2 = await uniCloud.httpclient.request(`https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2?access_token=${access_token}`,
		// {
		// 	method:'POST',
		// 	data:{
		// 		prompt:'睡莲',
		// 		width:1024,
		// 		height:1024,
		// 		version:'v2',
		// 	},
		// 	contentType: 'json', // 指定以application/json发送data内的数据
		// 	dataType: 'json' // 指定返回值为json格式，自动进行parse
		// })
		// return res2
		
		// const res3 = await uniCloud.httpclient.request(`https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImgv2?access_token=${access_token}`,
		// {task_id:res2.data.data.task_id})
		// return res3
		
		const mediaManager = uniCloud.ai.getMediaManager({
			provider: 'baidu',
			accessToken:access_token
		})
		const res1 = await mediaManager.imageGeneration({
		  prompt: '睡莲',
		  style: '赛博朋克',
		})
		const taskId = res1.taskId
		return taskId
		const res3 = await mediaManager.getGeneratedImage({
		  taskId,
		})
		return res3
	}
}
